package com.hxzy.common.util;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hxzy.common.vo.CodeEnum;
import com.hxzy.common.vo.R;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *  servlet工具类(springmvc)
 */
public class ServletUtil {

    public static ServletRequestAttributes getServletRequestAttributes(){
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes= (ServletRequestAttributes) attributes;
        return servletRequestAttributes;
    }


    public static HttpServletRequest  getRequest(){
        return getServletRequestAttributes().getRequest();
    }

    public static HttpServletResponse getResponse(){
        return getServletRequestAttributes().getResponse();
    }

    /**
     * 将字符串渲染到客户端
     *
     * @param response 渲染对象
     * @param string 待渲染的字符串
     * @return null
     */
    public static String renderString(HttpServletResponse response, String string)
    {
        try
        {
            response.setStatus(200);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.getWriter().print(string);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }

    public static  void outJson(HttpServletResponse response, CodeEnum codeEnum) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("html/text;charset=UTF-8");
        PrintWriter out=response.getWriter();
        //生成要输出的字符串
        R failed = R.failed(codeEnum);
//        //Jackson
//        ObjectMapper objectMapper=new ObjectMapper();
//        String jsonStr=objectMapper.writeValueAsString(failed);

        String jsonStr= JSONObject.toJSONString(failed);
        //输出给前端
        out.println(jsonStr);
        out.flush();
        out.close();
    }


}
